#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>
#include <QFile>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    textEdit = new QTextEdit(this);
    this->setCentralWidget(textEdit);
    centralWidget()->hide();
    posLabel = new QLabel(this);
    posLabel->setText("Welcome");
    statusBar()->addWidget(posLabel);
    connect(textEdit, SIGNAL(cursorPositionChanged()),
            this, SLOT(on_cursorPosChanged()));
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_actionOpen_triggered()
{
    filename = QFileDialog::getOpenFileName(this);
    this->setWindowTitle(filename + " - MyEditor");
    QFile file(filename);
    file.open(QIODevice::ReadOnly);
    textEdit->setText(file.readAll());
}

void MainWindow::on_actionClose_triggered()
{
    close();
}

void MainWindow::on_actionNew_triggered()
{
    centralWidget()->show();
}

void MainWindow::on_actionSave_triggered()
{
    if (filename == "")
    {
        filename = QFileDialog::getSaveFileName(this);
    }
    QFile file(filename);
    file.open(QIODevice::WriteOnly);
    file.write(textEdit->toPlainText().toUtf8());
    file.close();
}

void MainWindow::on_cursorPosChanged()
{
    posLabel->setNum(textEdit->textCursor().positionInBlock());
}
